#!/usr/bin/env python
# encoding: utf-8
# @Time    : 2020/4/22 10:12
# @Author  : Mr. Cui
# @File    : jenkins_api.py
# @Software: PyCharm
import os

from lxml import etree

from application import db
from application.apps.case_library.service.case_library_service import call_method
from application.apps.ci.service.client_api import sub_report_service
from application.libs import const
from application.libs.send_msg import *
from application.models.models import JobTask, Report, Taskcase
from application.settings import Config

PATH = Config.YAPI_REPORT_PATH


# PATH = Config.QR_DIR


class Job_yapi:
    def __init__(self, JOB_NAME, BUILD_ID):
        self.JOB_NAME = JOB_NAME
        self.BUILD_ID = str(BUILD_ID)
        self.dtoken = self.get_task_dtoken()

    def get_task_info(self, case_type):
        self.task_id = db.session.query(JobTask).filter(JobTask.job_name == self.JOB_NAME).first().id
        task = db.session.query(Taskcase).filter(Taskcase.task_id == self.task_id).all()
        # 用例对应的节点 返回
        ret = [[i.case.id, i.case.case_name, i.case.case_value, i.node_id] for i in task if
               i.case.case_type == case_type]
        return ret

    def get_task_dtoken(self):
        token = db.session.query(JobTask.ding_token).filter(JobTask.job_name == self.JOB_NAME).first()
        return token[0]

    def run_yapi(self, case_col, url, ):
        ret = requests.get(url, )
        path = PATH + 'html/yapi/' + self.JOB_NAME + "/" + str(self.BUILD_ID) + "/"
        if os.path.exists(path) is False:
            os.makedirs(path)
        path = path + case_col + '.html'
        html = ret.text
        print(path)
        with open(path, 'w', encoding='utf-8') as f:
            f.write(html)
        html = etree.HTML(html)
        len = str(html.xpath('//*[@id="right"]/div[1]/div/text()[1]')[0])

        len = filter(str.isdigit, str(len))
        ret_len = ""
        for i in len:
            ret_len += i

        successNum = html.xpath('//*[@id="right"]/div[1]/div/span/text()')[0]
        successNum = str(successNum).replace(" ", "")
        if ret_len == "":
            ret_len = successNum
            failedNum = 0
        else:
            failedNum = int(ret_len) - int(successNum)

        return case_col, ret_len, successNum, failedNum

    def write(self, task_id, case_id, total, succ, fail, info):

        report = Report(task_id=task_id, build_id=self.BUILD_ID, type=3, case_id=case_id, total=total, succ=succ,
                        fail=fail, err=0, is_ding=1, info=info)
        try:
            db.session.add(report)
            db.session.commit()
            return const.INSERT_SUCCESS
        except:
            db.session.rollback()
            return const.INSERT_FAIL

    def construct(self, JOB_NAME, BUILD_ID, TYPE, CASE_NAME, TOTAL, SUCC, FAIL, ERR, info):
        d = {1: "web_id", 2: "app_ui", 3: "接口"}

        ret_str = """JOB_NAME：%s
BUILD_ID：%s
TYPE: %s
CASE_NAME: %s
TOTAL：%s
SUCC：%s
FAIL：%s
ERR：%s
查看详情：%s""" % (JOB_NAME, BUILD_ID, d[TYPE], CASE_NAME, TOTAL, SUCC, FAIL, ERR, info)
        return str(ret_str)

    def ding_send(self, token, content):
        """

        :param token: 钉钉群token
        :param content:
        :return:
        """
        HEADERS = {"Content-Type": "application/json ;charset=utf-8 "}
        data = {"msgtype": "text", "text": {"content": content}, "at": {"atMobiles": [], "isAtAll": "false"}}
        data = json.dumps(data)
        res = requests.post(token, data=data, headers=HEADERS)
        return res.text

    def run(self, case_type=3):
        task_info = self.get_task_info(case_type)
        l = []
        for i in task_info:
            case_id = i[0]
            case_name = i[1]
            url = i[2]
            case_name, total, succ, fail = self.run_yapi(case_name, url)
            # info = '/ci/report/yapi/' + self.JOB_NAME + "/" + self.BUILD_ID + "/" + case_name + '.html'
            info = "http://" + Config.STATIC_SERVICE + "/html/yapi/" + self.JOB_NAME + "/" + self.BUILD_ID + "/" + case_name + '.html'
            self.write(self.task_id, case_id, total, succ, fail, info)
            construct = self.construct(self.JOB_NAME, self.BUILD_ID, case_type, case_name, total, succ, fail, 0, info)
            self.ding_send(self.dtoken, construct)
            l.append({case_name: "ok"})
        return l

    @staticmethod
    def get_task_type(JOB_NAME):
        task_id = db.session.query(JobTask).filter(JobTask.job_name == JOB_NAME).first().id
        task = db.session.query(Taskcase).filter(Taskcase.task_id == task_id).all()
        t_type = set([i.case.case_type for i in task])
        return t_type


class Job_ui(Job_yapi):

    def run_web_ui(self, case_id, node_id):
        #  +节点字段 IP/端口
        ret = call_method(case_id=case_id, sign="run", node_id=node_id, task_id=self.task_id, build_id=self.BUILD_ID)
        return ret

    def run(self, case_type=3):
        task_info = self.get_task_info(case_type)
        l = []
        for i in task_info:
            case_id = i[0]
            node_id = i[-1]
            ret = self.run_web_ui(case_id, node_id)
            l.append(ret)
            sub_report_service(self.task_id, self.BUILD_ID, case_id, case_type, 0, 0, 0, 0, info=0)
        return l


def jenkins_yapi(JOB_NAME, BUILD_ID):
    yapi = Job_yapi(JOB_NAME, BUILD_ID)
    ret = yapi.run()
    return ret


def jenkins_ui(JOB_NAME, BUILD_ID, case_type):
    yapi = Job_ui(JOB_NAME, BUILD_ID)
    ret = yapi.run(case_type)
    return ret


def jenkins_sonar(JOB_NAME, BUILD_ID):
    url = "https://sonar.360che.com/api/measures/search_history?component=transport-qa.360che.com&metrics=sqale_index%2Cduplicated_lines_density%2Cncloc%2Ccoverage%2Cbugs%2Ccode_smells%2Cvulnerabilities&ps=1000"
    ret = requests.get(url)
    bugs = ret.json()['measures'][0]['history'][-1]['value']
    Loophole = ret.json()['measures'][6]['history'][-1]['value']

    return bugs, Loophole


def jenkins_web_ui(JOB_NAME, BUILD_ID):
    pass


def jenkins_run(JOB_NAME, BUILD_ID):
    ret = jenkins_yapi(JOB_NAME, BUILD_ID)
    return ret


def task_sub_remind(JOB_NAME, BUILD_ID):
    """
    提交任务后钉钉提醒
    :return:
    """
    task_id, token = db.session.query(JobTask.id, JobTask.ding_token).filter(JobTask.job_name == JOB_NAME).first()
    content = """任务提交成功
JOB_NAME：%s
BUILD_ID：%s
聚合报告：http://%s/#/CITest/ci_report?task_id=%s&build_id=%s
""" % (JOB_NAME, BUILD_ID, Config.DOMAIN,task_id, BUILD_ID)

    HEADERS = {"Content-Type": "application/json ;charset=utf-8 "}
    data = {"msgtype": "text", "text": {"content": content}, "at": {"atMobiles": [], "isAtAll": "false"}}
    data = json.dumps(data)
    res = requests.post(token, data=data, headers=HEADERS)
    return res.text

def task_sub_remind_new(JOB_NAME, BUILD_ID):
    """
    提交任务后钉钉提醒,优化样式
    """
    task_id, token = db.session.query(JobTask.id, JobTask.ding_token).filter(JobTask.job_name == JOB_NAME).first()
    HEADERS = {"Content-Type": "application/json ;charset=utf-8 "}
    data = {
        "markdown": {
            "title": "项目部署完成，正在执行自动化测试...",
            "text": """
### 项目部署完成，正在执行自动化测试...
- 项目名称：%s
- BuildId：%s\n
[点击查看详情](http://%s/#/CITest/ci_report?task_id=%s&build_id=%s)
"""%(JOB_NAME, BUILD_ID,Config.DOMAIN,task_id, BUILD_ID),
            "btnOrientation": "0",
        },
        "msgtype": "markdown"
    }
    data = json.dumps(data)
    res = requests.post(token, data=data, headers=HEADERS)
    return res.text